package com.hsgene.user.controller.applets;

import com.hsgene.common.RangeType;
import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.basic.SimpleRegexUtils;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.user.domain.GeneticTestingUserMallAddress;
import com.hsgene.user.domain.SysArea;
import com.hsgene.user.exception.GeneticTestingUserMallAddressErrorCode;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.service.GeneticTestingUserMallAddressService;
import com.hsgene.user.service.api.GeneratorService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.user.controller.applets
 * @author: maodi
 * @createDate: 2018/10/12 10:21
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing")
public class GeneticTestingUserMallAddressController {

    private static Logger LOGGER = LogManager.getLogger(GeneticTestingUserMallAddressController.class);

    @Resource
    GeneticTestingUserMallAddressService geneticTestingUserMallAddressService;

    @Resource
    GeneratorService generatorService;

    /**
     * @param
     * @return com.hsgene.common.util.result.ApiResult<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     * @description 获取大区下拉框数据源
     * @author maodi
     * @createDate 2018/11/8 14:03
     */
    @GetMapping("regions")
    public ApiResult<List<Map<String, Object>>> regions() {
        try {
            return ApiResult.succ(geneticTestingUserMallAddressService.selectRegions());
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.SELECT_REGIONS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.SELECT_REGIONS_IS_ERROR);
        }
    }

    /**
     * @param regionId 大区id
     * @return com.hsgene.common.util.result.ApiResult<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     * @description 根据大区id获取省份下拉框数据
     * @author maodi
     * @createDate 2018/11/8 14:10
     */
    @GetMapping("provinces/{region_id}")
    public ApiResult<List<Map<String, Object>>> provincesByRegionId(@PathVariable("region_id") String regionId) {
        try {
            if (StringUtils.isBlank(regionId)) {
                return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.REGION_ID_IS_NOT_NULL);
            }
            return ApiResult.succ(geneticTestingUserMallAddressService.selectProvincesByRegionId(regionId));
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.SELECT_PROVINCES_BY_REGION_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.SELECT_PROVINCES_BY_REGION_ID_IS_ERROR);
        }
    }

    /**
     * @param
     * @return java.util.List<com.hsgene.user.domain.SysArea>
     * @description 获取所有省(直辖市)列表
     * @author maodi
     * @createDate 2018/10/12 11:23
     */
    @GetMapping("address")
    public ApiResult<List<SysArea>> getProvinceAddress() {
        try {
            List<SysArea> list = geneticTestingUserMallAddressService.getProvinceAddress();
            list.sort(Comparator.comparing(SysArea::getIdToInteger));
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.RECIPIENT_SAMPLE_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.RECIPIENT_SAMPLE_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param parentId
     * @return java.util.List<com.hsgene.user.domain.SysArea>
     * @description 根据id获取地址
     * @author maodi
     * @createDate 2018/10/12 11:24
     */
    @GetMapping("address/{parent_id}")
    public ApiResult<List<SysArea>> getAddressByParentId(@PathVariable("parent_id") String parentId) {
        try {
            if (StringUtils.isBlank(parentId)) {
                return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.PARENT_ID_IS_NULL);
            }
            List<SysArea> list = geneticTestingUserMallAddressService.getAddressByParentId(parentId);
            list.sort(Comparator.comparing(SysArea::getIdToInteger));
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.RECIPIENT_SAMPLE_ADDRESS_IS_ERROR.getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.RECIPIENT_SAMPLE_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 根据用户id获取收货取样地址列表
     * @author maodi
     * @createDate 2018/10/11 16:15
     */
    @GetMapping("users/mall/address")
    public ApiResult<List<GeneticTestingUserMallAddress>> getGeneticTestingUserMallAddressList(
            @FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(UserErrorCode.USER_ID_IS_NULL);
            }
            List<GeneticTestingUserMallAddress> list = geneticTestingUserMallAddressService
                    .getGeneticTestingUserMallAddressByUserId(userId);
            list.sort((GeneticTestingUserMallAddress o1, GeneticTestingUserMallAddress o2) -> o2.getIsDefault() -
                                                                                              o1.getIsDefault());
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.GET_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR
                    .getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                    .GET_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param geneticTestingUserMallAddress 收货取样地址信息
     * @param userInfo                      用户信息
     * @return com.hsgene.common.util.result.ApiResult
     * @description 新增发票信息
     * @author maodi
     * @createDate 2018/10/11 16:16
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PostMapping("users/mall/address")
    public ApiResult<NullObject> insertGeneticTestingUserMallAddress(
            @RequestBody GeneticTestingUserMallAddress geneticTestingUserMallAddress,
            @FromSession UserInfo userInfo) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            geneticTestingUserMallAddress.setUserId(userId);
            ErrorCode code = checkGeneticInvoice(geneticTestingUserMallAddress, null);
            if (code != null) {
                return ApiResult.fail(code);
            }
            String id = generatorService.getGenerator("", "").getData().getSerialNumber();
            geneticTestingUserMallAddress.setId(id);
            geneticTestingUserMallAddressService.insertGeneticTestingUserMallAddress(geneticTestingUserMallAddress);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.INSERT_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR
                    .getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                    .INSERT_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param geneticTestingUserMallAddress 收货取样地址信息
     * @param id                            收货取样地址id
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 验证收货取样地址信息信息是否合格
     * @author maodi
     * @createDate 2018/10/11 17:49
     */
    private ErrorCode checkGeneticInvoice(GeneticTestingUserMallAddress geneticTestingUserMallAddress, String id) {
        String userId = geneticTestingUserMallAddress.getUserId();
        if (StringUtils.isBlank(userId)) {
            return CommonErrorCode.USER_ID_IS_NULL;
        }
        if (geneticTestingUserMallAddress == null) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_IS_NULL;
        }
        String address = geneticTestingUserMallAddress.getAddress();
        //判断地址是否为空
        if (StringUtils.isBlank(address)) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_ADDRESS_IS_NULL;
        }
        //判断省级id是否为空
        String provinceId = geneticTestingUserMallAddress.getProvinceId();
        if (StringUtils.isBlank(provinceId)) {
            return GeneticTestingUserMallAddressErrorCode.PROVINCE_ID_IS_NULL;
        }
        //判断区县级id是否为空
        String districtId = geneticTestingUserMallAddress.getDistrictId();
        if (StringUtils.isBlank(districtId)) {
            return GeneticTestingUserMallAddressErrorCode.DISTRICT_ID_IS_NULL;
        }
        String cityId = geneticTestingUserMallAddress.getCityId();
        if (StringUtils.isBlank(cityId)) {
            cityId = null;
        }
        //判断地址是否重复
        int addressCount = geneticTestingUserMallAddressService.getCountByAddressAndUserId(address, userId, id,
                provinceId, cityId, districtId);
        if (addressCount > 0) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_ADDRESS_IS_EXIST;
        }
        String signerName = geneticTestingUserMallAddress.getSignerName();
        //判断收件人是否为空
        if (StringUtils.isBlank(signerName)) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_SIGNER_NAME_IS_NULL;
        }
        String phone = geneticTestingUserMallAddress.getPhone();
        //判断联系方式是否为空
        if (StringUtils.isBlank(phone)) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_PHONE_IS_NULL;
        }
        //判断联系方式是否为手机或者座机
        if (!SimpleRegexUtils.isMobile(phone) && !SimpleRegexUtils.isTelephone(phone)) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_PHONE_IS_NOT_PHONE;
        }
        //判断备注是否超过200字符
        String remarks = geneticTestingUserMallAddress.getRemarks();
        if (StringUtils.isNotBlank(remarks)) {
            if (remarks.length() > 200) {
                return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_REMARKS_IS_EXCEED_200;
            }
        }
        return null;
    }

    /**
     * @param geneticTestingUserMallAddress 收货取样地址信息
     * @param userInfo                      用户信息
     * @param rangeType                     范围类型
     * @param userMallAddressId             收货/取样地址id
     * @return com.hsgene.common.util.result.ApiResult
     * @description 修改收货取样地址信息
     * @author maodi
     * @createDate 2018/10/11 16:17
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @PutMapping("users/mall/address/{user_mall_address_id}")
    public ApiResult<List<GeneticTestingUserMallAddress>> updateGeneticTestingUserMallAddress(
            @RequestBody(required = false) GeneticTestingUserMallAddress geneticTestingUserMallAddress,
            @FromSession UserInfo userInfo,
            @RequestParam("range_type") String rangeType,
            @PathVariable("user_mall_address_id") String userMallAddressId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(rangeType)) {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_NULL);
            }
            //修改当前用户其他地址信息为未默认，此地址为默认
            if (RangeType.PART.getMessage().equals(rangeType)) {
                if (StringUtils.isBlank(userMallAddressId)) {
                    return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                            .GENETIC_TESTING_USER_MALL_ADDRESS_ID_IS_NULL);
                }
                geneticTestingUserMallAddressService.updateGeneticTestingUserMallAddressToDefault(userMallAddressId,
                        userId);
            } else if (RangeType.ALL.getMessage().equals(rangeType)) {
                geneticTestingUserMallAddress.setId(userMallAddressId);
                geneticTestingUserMallAddress.setUserId(userId);
                ErrorCode code = checkUpdateGeneticTestingUserMallAddress(geneticTestingUserMallAddress);
                if (code != null) {
                    return ApiResult.fail(code);
                }
                geneticTestingUserMallAddressService.updateGeneticTestingUserMallAddress(geneticTestingUserMallAddress);
            } else {
                return ApiResult.fail(CommonErrorCode.RANGE_TYPE_IS_ERROR);
            }
            List<GeneticTestingUserMallAddress> list = geneticTestingUserMallAddressService
                    .getGeneticTestingUserMallAddressByUserId(userId);
            list.sort((GeneticTestingUserMallAddress o1, GeneticTestingUserMallAddress o2) -> o2.getIsDefault() -
                                                                                              o1.getIsDefault());
            return ApiResult.succ(list);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.UPDATE_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR
                    .getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                    .UPDATE_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param geneticTestingUserMallAddress 收货取样地址信息
     * @return com.hsgene.common.util.exception.ErrorCode
     * @description 检查更新收货取样地址信息是否合格
     * @author maodi
     * @createDate 2018/10/11 17:53
     */
    private ErrorCode checkUpdateGeneticTestingUserMallAddress(
            GeneticTestingUserMallAddress geneticTestingUserMallAddress) {
        if (geneticTestingUserMallAddress == null) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_IS_NULL;
        }
        String id = geneticTestingUserMallAddress.getId();
        if (StringUtils.isBlank(id)) {
            return GeneticTestingUserMallAddressErrorCode.GENETIC_TESTING_USER_MALL_ADDRESS_ID_IS_NULL;
        }
        return checkGeneticInvoice(geneticTestingUserMallAddress, id);
    }

    /**
     * @param userInfo          用户信息
     * @param userMallAddressId 收货/取样地址id
     * @return com.hsgene.common.util.result.ApiResult
     * @description 根据收货取样地址id删除收货取样地址信息
     * @author maodi
     * @createDate 2018/10/11 16:18
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    @DeleteMapping("users/mall/address/{user_mall_address_id}")
    public ApiResult<NullObject> deleteGeneticTestingUserMallAddress(
            @FromSession UserInfo userInfo,
            @PathVariable("user_mall_address_id") String userMallAddressId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(userMallAddressId)) {
                return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                        .GENETIC_TESTING_USER_MALL_ADDRESS_ID_IS_NULL);
            }
            GeneticTestingUserMallAddress geneticTestingUserMallAddress = geneticTestingUserMallAddressService
                    .getGeneticTestingUserMallAddressById(userId, userMallAddressId);
            if (geneticTestingUserMallAddress == null || StringUtils.isBlank(geneticTestingUserMallAddress.getId())) {
                return ApiResult.fail(GeneticTestingUserMallAddressErrorCode.HAVE_BEEN_DELETED);
            }
            geneticTestingUserMallAddressService.deleteGeneticTestingUserMallAddressById(userMallAddressId);
            return ApiResult.succ();
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.DELETE_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR
                    .getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                    .DELETE_GENETIC_TESTING_USER_MALL_ADDRESS_IS_ERROR);
        }
    }

    /**
     * @param userInfo          用户信息
     * @param userMallAddressId 收货/取样地址id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.user.domain.GeneticTestingUserMallAddress>
     * @description 根据收货/取样地址id获取收货/取样地址信息
     * @author maodi
     * @createDate 2018/10/16 16:46
     */
    @GetMapping("users/mall/address/{user_mall_address_id}")
    public ApiResult<GeneticTestingUserMallAddress> getGeneticTestingUserMallAddressById(
            @FromSession UserInfo userInfo,
            @PathVariable("user_mall_address_id") String userMallAddressId) {
        try {
            if (userInfo == null) {
                return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
            }
            String userId = userInfo.getUserId();
            if (StringUtils.isBlank(userId)) {
                return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
            }
            if (StringUtils.isBlank(userMallAddressId)) {
                return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                        .GENETIC_TESTING_USER_MALL_ADDRESS_ID_IS_NULL);
            }
            GeneticTestingUserMallAddress geneticTestingUserMallAddress = geneticTestingUserMallAddressService
                    .getGeneticTestingUserMallAddressById(userId, userMallAddressId);
            if (geneticTestingUserMallAddress == null || geneticTestingUserMallAddress.getId() == null) {
                return ApiResult.succ(geneticTestingUserMallAddress, "没有找到该id的收货/取样地址信息");
            }
            return ApiResult.succ(geneticTestingUserMallAddress);
        } catch (Exception e) {
            LOGGER.error(GeneticTestingUserMallAddressErrorCode.GET_GENETIC_TESTING_USER_MALL_ADDRESS_BY_ID_IS_ERROR
                    .getMessage(), e);
            return ApiResult.fail(GeneticTestingUserMallAddressErrorCode
                    .GET_GENETIC_TESTING_USER_MALL_ADDRESS_BY_ID_IS_ERROR);
        }
    }

}
